package com.shxy.rlzy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.shxy.rlzy.entity.*;
import com.shxy.rlzy.mapper.*;
import com.shxy.rlzy.service.IAuthoritySerivce;
import com.shxy.rlzy.service.IUserRoleService;
import com.shxy.rlzy.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shxy.rlzy.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author tanhao
 * @since 2021-08-16
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    private UserMapper userMapper;      // 用户管理

    private UserRoleMapper userRoleMapper;  // 用户角色
    private RedisUtil redisUtil;        // redis工具
    private BCryptPasswordEncoder passwordEncoder;
    @Autowired
    private IAuthoritySerivce authoritySerivce;

    @Autowired
    public void setUserRoleMapper(UserRoleMapper userRoleMapper) {
        this.userRoleMapper = userRoleMapper;
    }

    @Autowired
    public void setPasswordEncoder(BCryptPasswordEncoder passwordEncoder) {
        this.passwordEncoder = passwordEncoder;
    }
    @Autowired
    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Autowired
    public void setRedisUtil(RedisUtil redisUtil) {
        this.redisUtil = redisUtil;
    }
    @Override
    public User getByUsername(String username) {
        return getOne(new QueryWrapper<User>().eq("username", username));
    }

    @Override
    public User getByPhone(String phone) {
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("phone", phone);
        return userMapper.selectOne(qw);
    }

    /**
     * 获取用户权限列表
     * @param userId 用户编号
     * @return
     */
    @Override
    public String getUserAuthorities(Long userId) {
        // 根据用户编号获取用户信息
        User user = userMapper.selectById(userId);
        // 构造redis键
        String redisKey = "GrantedAuthority:" + user.getUsername();

        // 如果缓存中有该权限，则直接返回
        if(redisUtil.hasKey(redisKey)) {
            return (String) redisUtil.get(redisKey);
        }

        String authorities = authoritySerivce.getAuthoritiesByUserId(userId);

        // 将用户权限保存到redis中
        redisUtil.set(redisKey, authorities, 60 * 60);

        return authorities;
    }

    @Override
    public boolean customSave(User user) {
        user.setUpdated(LocalDateTime.now()); // 设置更新时间
        // 如果是新增，则设置默认密码
        if(user.getId() == null || user.getId() == 0) {
            user.setPassword(passwordEncoder.encode("123456"));
        }
        // 保存用户信息
        return this.saveOrUpdate(user);
    }

    @Override
    public Role getRoleByUserId(Long userId) {
        return userRoleMapper.getRoleByUserId(userId);
    }

    @Override
    public User importFromEmployee(EmployeeInfo employeeInfo) {
        // 1、根据电话查询用户是否存在
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("phone", employeeInfo.getPhone());
        User user = this.getOne(qw);
        // 2、如果用户不存在，则添加用户
        if(user == null) {
            user = new User();
            user.setUsername(employeeInfo.getPhone());
            user.setPassword(passwordEncoder.encode(employeeInfo.getIdCard().substring(12)));
            user.setPhone(employeeInfo.getPhone());
            if(this.save(user)) {
                return getByPhone(user.getPhone());
            }
        }
        return user;
    }

    @Override
    public boolean changePassword(String username, String newPwd) {
        UpdateWrapper<User> uw = new UpdateWrapper<>();
        uw.eq("username", username);

        User user = new User();
        user.setPassword(passwordEncoder.encode(newPwd));

        return update(user, uw);
    }

    @Override
    public boolean resetPassword(Long userId) {
        UpdateWrapper<User> uw = new UpdateWrapper<>();
        uw.eq("id", userId);

        User user = new User();
        user.setPassword(passwordEncoder.encode("123456"));

        return update(user, uw);
    }
}
